package com.cctv.haierstore.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.cctv.common.to.es.SkuEsModel;
import com.cctv.haierstore.search.config.HaierStoreElasticConfig;
import com.cctv.haierstore.search.constant.EsConstant;
import com.cctv.haierstore.search.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author huayi
 * @date 2023年11月26日 23:13
 */
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String skuInfo = JSON.toJSONString(skuEsModel);
            indexRequest.source(skuInfo, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, HaierStoreElasticConfig.COMMON_OPTIONS);
        return bulk.hasFailures();
    }
}
